package vip.zhenzicheng.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * BIO 通信的服务端(未优化，显示创建线程)
 *
 * @author zhenzicheng
 * @date: 2022-06-01 15:27
 */
public class Server {

  private static final Logger LOG = Logger.getLogger(Server.class.getSimpleName());

  public static void main(String[] args) throws IOException {

    try ( // try-with-resources 模式会自动close声明的资源
          ServerSocket serverSocket = new ServerSocket()) {
      serverSocket.bind(new InetSocketAddress(10001));
      LOG.info("Start Server ......");
      while (true) {
        new Thread(new ServerTask(serverSocket.accept())).start();
      }
    }

  }

  static class ServerTask implements Runnable {

    private final Socket socket;

    public ServerTask(Socket socket) {
      this.socket = socket;
    }

    @Override
    public void run() {
      try (
          ObjectOutputStream outputStream = new ObjectOutputStream(this.socket.getOutputStream());
          ObjectInputStream inputStream = new ObjectInputStream(this.socket.getInputStream())
      ) {
        String msg = inputStream.readUTF();
        LOG.info("Accept client message: " + msg);

        outputStream.writeUTF("ok");
        outputStream.flush();

      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

}
